using UnityEngine;
using System.Collections;

public class Networking : MonoBehaviour {
	
	
	public GameObject p1;
	public GameObject p2;
	public string p2ip;
	public bool activated;
	
	private int connectAttempts;
	private NetworkPlayer p2Network;
	private float timer;
	private bool connectedToServer;
	private bool isServer;
	

	// Use this for initialization
	void Start () {
		
		timer = 0;
		connectedToServer = false;
		isServer = false;
		connectAttempts = 0;
		DataManager.Instance.networkingActivated = activated;
		
		
	}
	
	// Update is called once per frame
	void Update () {
	
		if(!activated)return;
		if(!isServer && !connectedToServer)
		{
			timer += Time.deltaTime;
			
			if(timer>0.5f)
			{
				connectToServer();			
				timer = 0;
				connectAttempts++;
				print ("Connect Attempt: "+connectAttempts);
				if(connectAttempts>4)
				{
					print ("Well fuck this we'll make our own server >:D");	
					createServer();
				
				}
			}
			
			
		}else
		{			
			networkView.RPC ("receivePlayerData",RPCMode.OthersBuffered,p1.transform.position,p1.transform.rotation);	
		}
		
		
	
		
	
	}
	
	void OnServerInitialized()
	{
		print ("Server is up and running");
		
		
		isServer = true;
		DataManager.Instance.isServer = true;
	}
	
	[RPC]
	void receivePlayerData(Vector3 pos, Quaternion rotation)
	{
		p2.transform.position = pos;
		p2.transform.rotation = rotation;
	}
	
	void OnConnectedToServer()
	{
		print("Connected to Server!!");			
		connectedToServer = true;
		p1.transform.position = new Vector3(10,0,0);
		DataManager.Instance.isRunning = true;
		
		
	}
	
	void OnPlayerConnected(NetworkPlayer player)
	{
			print ("Player connected: " + player.ipAddress);
			p2Network = player;
			p1.transform.position = new Vector3(0,0,0);
			DataManager.Instance.isRunning = true;
	}
	
	
	void connectToServer()
	{	
		Network.Connect(p2ip,1337);
	}
	
	
	
	void createServer()
	{	
		Network.InitializeServer(3,1337);			
	}
}
